package com.imooc.infra.repository;

import com.imooc.business.domain.Rule;
import com.imooc.infra.mapping.RuleMapping;
import com.imooc.infra.repository.entity.TDataCenterRule;
import com.imooc.infra.repository.service.ITDataCenterRuleService;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Repository
public class RuleRepository {

    @Setter(onMethod_ = @Autowired)
    private ITDataCenterRuleService ruleService;

    @Setter(onMethod_ = @Autowired)
    private RuleMapping ruleMapping;

    public Rule getRuleByBusinessIdAndRuleType(String businessId, String ruleType) {
        TDataCenterRule rule = ruleService.getByBusinessIdAndRuleType(businessId, ruleType);
        return Optional.ofNullable(rule).map(ruleMapping::toVo).orElse(null);
    }

    public List<String> listBusinessIds() {
        return ruleService.listBusinessIds();
    }

    public Rule save(Rule rule) {
        TDataCenterRule tDataCenterRule = ruleMapping.toEntity(rule);
        boolean save = ruleService.save(tDataCenterRule);
        if (save) {
            rule.setRuleId(tDataCenterRule.getId());
            return rule;
        }
        return null;
    }

    public List<Rule> listAll() {
        List<TDataCenterRule> rules = ruleService.listAll();
        return ruleMapping.toVos(rules);
    }
}
